package com.duowan.cms.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;


/**
 * 
 * <p>作　　者：黄均杨
 * <p>完成日期：2012-11-11
 */
public class CommandLineTools {
	private static String OS= System.getProperty("os.name").toLowerCase().startsWith("windows") ? "windows"
				: "linux";

	public static String getOS() {
		return OS;
	}

	/**
	 * 在单独的进程中执行指定的字符串命令
	 * @param cmd 字符串命令
	 * @return
	 */
	public static String execCommand(String cmd) throws java.io.IOException,
			java.lang.InterruptedException {
		String[] cmds;
		if (OS.equals("windows")) {
			cmds = new String[] { "cmd.exe", "/c", cmd };
		} else {
			cmds = new String[] { "/bin/sh", "-c", cmd };
		}
		return execCommand(cmds);
	}
	
	/**
	 * 在单独的进程中执行指定命令集合。
	 * @param cmds 指定的命令 加上参数
	 * @return
	 */
	private  static String execCommand(String[] cmds)
			throws java.io.IOException, java.lang.InterruptedException {
		Process process = null;
		int result = 0;  
		StringBuilder resultBuilder = new StringBuilder("");
		try { 
			ProcessBuilder processBuilder = new ProcessBuilder(cmds);
			processBuilder.redirectErrorStream(true);
			process = processBuilder.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream() , "GBK"));               
			String output = null;                                                                                  
			while (null != (output = br.readLine())){                
				resultBuilder.append(output);
				//System.out.println(output);                                                                          
			}                                                                                                      
			result = process.waitFor();                                                                                
		} catch (Exception e) {  
			e.printStackTrace();
        }  
		//return (result == 0) ? "正常结束" : ("非正常结束"+ String.valueOf(result))  ;
		return resultBuilder.toString();
	}
	

}
